<template>
    <div id='wrap'>
        <h1>计算属性computed</h1>
        <!-- 普通函数计算重复次数 -->
        <div>在模板中计算：{{ author.books.length > 1 ? author.books.join('-') : author.books[0] }}</div>
        <input type="text" v-model="bookName">
        <button @click="addNewBOok">新增一本武林秘籍</button>


        <!-- 比较普通函数和计算属性 -->
        <div>普通函数</div>
        <div v-for="item in 3" :key="item">
            <p>{{ funcBooksStr() }}</p>
        </div>
        <hr>
        <div>计算属性</div>
        <div v-for="item in 3" :key="item">
            <p>{{ compBooksStr }}</p>
        </div>
    </div>
</template>
<script lang='ts'>
export default {
    name: 'computed',
}
</script>
<script lang='ts' setup>
import { ref, h, type Ref, isRef, reactive, isReactive, readonly, isReadonly, toRef, toRefs, unref, isProxy, computed } from 'vue';

const bookName = ref('')
const author = reactive({
    name: '王小绿',
    books: ['《Vue3从入门到入土》', '《TypeScript从入门到出门》']
})
const addNewBOok = () => {
    try {
        if (!bookName.value) {
            throw new Error('请输入书名')
        }
        console.log('模拟计算属性')
        author.books.push(bookName.value)
    } catch (error: any) {
        alert(error.msg)
    }
}


//计算属性和普通函数对比
const books = reactive(['Book A', 'Book B', 'Book C'])
const funcBooksStr = function () {
    console.log('普通函数被调用');
    return books.length > 1 ? books.join('-') : books[0]
}
const compBooksStr = computed(() => {
    console.log('计算属性被调用');
    return books.length > 1 ? books.join('-') : books[0]
})

//只读属性计算
const user = reactive({
    firstName: '小明',
    lastName: '小绿'
});
const fullNmae = computed(() => {
    console.log('触发计算')
    return `${user.firstName}${user.lastName}`;
})
</script>
<style lang='scss'>
@use '@/assets/common.scss';
</style>